<template>
  <LayoutContainer class="application-manage">
    <ContentContainer>
      <template #header>
        <FolderBreadcrumb :folderList="folderList" @click="folderClickHandle" />
      </template>
      <template #search>
        <!-- 搜索部分 -->
        <div class="flex">
          <div class="flex-between complex-search">
            <el-input
              v-model="search_form.name"
              @change="searchHandle"
              :placeholder="$t('common.searchBar.placeholder')"
              style="width: 350px"
              clearable
            />
          </div>
        </div>
      </template>

      <!-- 创建按钮和应用列表在同一区域 -->
      <div
        v-loading.fullscreen.lock="paginationConfig.current_page === 1 && loading"
        style="max-height: calc(100vh - 120px); padding: 0 16px 16px 16px;"
      >
        <InfiniteScroll
          :size="applicationList.length"
          :total="paginationConfig.total"
          :page_size="paginationConfig.page_size"
          v-model:current_page="paginationConfig.current_page"
          @load="getList"
          :loading="loading"
        >
          <el-row :gutter="15" class="w-full" v-if="applicationList.length > 0">
            <!-- 创建按钮 -->
            <el-col
              :xs="24"
              :sm="12"
              :md="12"
              :lg="8"
              :xl="6"
              class="mb-16"
              v-if="permissionPrecise.create()"
            >
              <CardBox class="cursor create-button-card">
                <template #icon>
                  <el-avatar shape="square" :size="32" style="background: none;" class="create-icon">
                    <el-icon style="font-size: 32px; color: #409EFF;"><plus /></el-icon>
                  </el-avatar>
                </template>
                <template #title>
                  <div class="text-center">
                    <span style="color: #409EFF;">{{ $t('common.create') }}</span>
                  </div>
                </template>
                <el-dropdown trigger="click" placement="bottom" class="w-full">
                  <div class="w-full h-full create-button-inner"></div>
                  <template #dropdown>
                    <el-dropdown-menu class="create-dropdown">
                      <el-dropdown-item @click="openCreateDialog()">
                        <div class="flex align-center">
                          <el-avatar class="avatar-blue" shape="square" :size="32">
                            <img src="@/assets/application/icon_simple_application.svg" style="width: 58%" alt="" />
                          </el-avatar>
                          <div class="pre-wrap ml-8">
                            <div class="lighter">{{ $t('views.application.createApplication') }}</div>
                          </div>
                        </div>
                      </el-dropdown-item>
                      <el-dropdown-item @click="openCreateFolder()">
                        <div class="flex align-center">
                          <el-avatar class="avatar-gray" shape="square" :size="32">
                            <img src="@/assets/knowledge/icon_file-folder_colorful.svg" style="width: 58%" alt="" />
                          </el-avatar>
                          <div class="pre-wrap ml-8">
                            <div class="lighter">{{ $t('views.application.createFolder') }}</div>
                          </div>
                        </div>
                      </el-dropdown-item>
                      <el-upload
                        ref="elUploadRef"
                        :file-list="[]"
                        action="#"
                        multiple
                        :auto-upload="false"
                        :show-file-list="false"
                        :limit="1"
                        :on-change="(file: any, fileList: any) => importApplication(file)"
                        class="import-button"
                      >
                        <el-dropdown-item>
                          <div class="flex align-center">
                            <el-avatar class="avatar-green" shape="square" :size="32">
                              <img src="@/assets/icon_import.svg" style="width: 58%" alt="" />
                            </el-avatar>
                            <div class="pre-wrap ml-8">
                              <div class="lighter">{{ $t('views.application.importApplication') }}</div>
                            </div>
                          </div>
                        </el-dropdown-item>
                      </el-upload>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </CardBox>
            </el-col>
            
            <!-- 应用列表项 -->
            <template v-for="(item, index) in applicationList" :key="index">
              <el-col
                v-if="item.resource_type === 'folder'"
                :xs="24"
                :sm="12"
                :md="12"
                :lg="8"
                :xl="6"
                class="mb-16"
              >
                <CardBox
                  :title="item.name"
                  :description="item.desc || $t('components.noDesc')"
                  class="cursor"
                  @click="clickFolder(item)"
                >
                  <template #icon>
                    <el-avatar shape="square" :size="32" style="background: none">
                      <AppIcon iconName="app-folder" style="font-size: 32px"></AppIcon>
                    </el-avatar>
                  </template>
                </CardBox>
              </el-col>
              <el-col
                v-else
                :xs="24"
                :sm="12"
                :md="12"
                :lg="8"
                :xl="6"
                class="mb-16"
              >
                <CardBox
                  :title="item.name"
                  :description="item.description || $t('components.noDesc')"
                  class="cursor"
                  @click="goApp(item)"
                >
                  <template #icon>
                    <el-avatar v-if="item.icon" shape="square" :size="32" style="background: none">
                      <img :src="resetUrl(item.icon)" alt="" />
                    </el-avatar>
                    <el-avatar v-else :name="item.name" pinyinColor shape="square" :size="32" />
                  </template>
                  <template #subTitle>
                    <div class="flex justify-between items-center w-full">
                      <el-text class="color-secondary" size="small">
                        {{ getSubTitle(item) }}
                      </el-text>
                      <el-tag v-if="item.publish_status === 'published'" type="success" size="small">
                        {{ $t('common.published') }}
                      </el-tag>
                    </div>
                  </template>
                  <template #footer>
                    <div class="flex justify-between items-center w-full">
                      <span class="card-footer-left color-secondary">
                        {{ $t('common.creator') }}: {{ item.create_user_nick_name }}
                      </span>
                      <el-dropdown
                        @command="(command: string) => handleCommand(command, item)"
                        trigger="click"
                        placement="bottom"
                      >
                        <el-button size="small" circle>
                          <el-icon><more /></el-icon>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="setting">
                              <el-icon><setting /></el-icon>
                              {{ $t('common.setting') }}
                            </el-dropdown-item>
                            <el-dropdown-item command="authorization">
                              <el-icon><key /></el-icon>
                              {{ $t('common.authorization') }}
                            </el-dropdown-item>
                            <el-dropdown-item command="copy">
                              <el-icon><copy /></el-icon>
                              {{ $t('common.copy') }}
                            </el-dropdown-item>
                            <el-dropdown-item command="move" v-if="apiType === 'workspace'">
                              <el-icon><location /></el-icon>
                              {{ $t('common.move') }}
                            </el-dropdown-item>
                            <el-dropdown-item command="export">
                              <el-icon><download /></el-icon>
                              {{ $t('common.export') }}
                            </el-dropdown-item>
                            <el-dropdown-item command="delete" danger>
                              <el-icon><delete /></el-icon>
                              {{ $t('common.delete') }}
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </template>
                </CardBox>
              </el-col>
            </template>
          </el-row>
          <el-empty :description="$t('common.noData')" v-else />
        </InfiniteScroll>
      </div>
    </ContentContainer>

    <!-- 其他弹窗 -->
    <CreateApplicationDialog ref="CreateApplicationDialogRef" />
    <CopyApplicationDialog ref="CopyApplicationDialogRef" />
    <CreateFolderDialog ref="CreateFolderDialogRef" @refresh="refreshFolder" />
    <MoveToDialog
      ref="MoveToDialogRef"
      :source="SourceTypeEnum.APPLICATION"
      @refresh="refreshApplicationList"
      v-if="apiType === 'workspace'"
    />
    <ResourceAuthorizationDrawer
      :type="SourceTypeEnum.APPLICATION"
      ref="ResourceAuthorizationDrawerRef"
    />
  </LayoutContainer>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive, computed } from 'vue'
import CreateApplicationDialog from '@/views/application/component/CreateApplicationDialog.vue'
import CreateFolderDialog from '@/components/folder-tree/CreateFolderDialog.vue'
import CopyApplicationDialog from '@/views/application/component/CopyApplicationDialog.vue'
import MoveToDialog from '@/components/folder-tree/MoveToDialog.vue'
import ResourceAuthorizationDrawer from '@/components/resource-authorization-drawer/index.vue'
import ApplicationApi from '@/api/application/application'
import { MsgSuccess, MsgConfirm, MsgError } from '@/utils/message'
import useStore from '@/stores'
import { t } from '@/locales'
import { useRouter, useRoute } from 'vue-router'
import { isWorkFlow } from '@/utils/application'
import { resetUrl } from '@/utils/common'
import { dateFormat } from '@/utils/time'
import { SourceTypeEnum } from '@/enums/common'
import permissionMap from '@/permission'
import WorkspaceApi from '@/api/workspace/workspace'
import { hasPermission } from '@/utils/permission'
import { ComplexPermission } from '@/utils/permission/type'
import { EditionConst, PermissionConst, RoleConst } from '@/utils/permission/data'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()

const apiType = computed<'workspace'>(() => {
  return 'workspace'
})
const permissionPrecise = computed(() => {
  return permissionMap['application'][apiType.value]
})

const { folder, application, user } = useStore()

const loading = ref(false)

// 处理卡片操作命令
function handleCommand(command: string, item: any) {
  switch (command) {
    case 'setting':
      settingApplication(item)
      break
    case 'authorization':
      openAuthorization(item)
      break
    case 'copy':
      copyApplication(item)
      break
    case 'move':
      openMoveToDialog(item)
      break
    case 'export':
      exportApplication(item)
      break
    case 'delete':
      deleteApplication(item)
      break
    case 'chat':
      toChat(item)
      break
    default:
      break
  }
}

// 获取应用卡片子标题
function getSubTitle(item: any) {
  if (isWorkFlow(item.type)) {
    return t('views.application.workflow')
  }
  switch (item.type) {
    case 'NORMAL':
      return t('views.application.normal')
    case 'API':
      return t('views.application.api')
    case 'KNOWLEDGE':
      return t('views.application.knowledge')
    default:
      return t('views.application.normal')
  }
}

const search_form = ref<any>({
  name: '',
})



const paginationConfig = reactive({
  current_page: 1,
  page_size: 30,
  total: 0,
})

const folderList = ref<any[]>([])
const applicationList = ref<any[]>([])
const CopyApplicationDialogRef = ref()

const ResourceAuthorizationDrawerRef = ref()
function openAuthorization(item: any) {
  ResourceAuthorizationDrawerRef.value.open(item.id)
}

const MoveToDialogRef = ref()

function openMoveToDialog(data: any) {
  const obj = {
    id: data.id,
    folder_id: data.folder,
  }
  MoveToDialogRef.value?.open(obj)
}

function refreshApplicationList(row: any) {
  const index = applicationList.value.findIndex((v) => v.id === row.id)
  applicationList.value.splice(index, 1)
}

const goApp = (item: any) => {
  router.push({ path: get_route(item) })
}

const get_route = (item: any) => {
  if (
    hasPermission(
      [
        new ComplexPermission(
          [RoleConst.USER],
          [PermissionConst.APPLICATION.getApplicationWorkspaceResourcePermission(item.id)],
          [],
          'AND',
        ),
        RoleConst.WORKSPACE_MANAGE.getWorkspaceRole,
        PermissionConst.APPLICATION_OVERVIEW_READ.getWorkspacePermissionWorkspaceManageRole,
        PermissionConst.APPLICATION_OVERVIEW_READ.getApplicationWorkspaceResourcePermission(
          item.id,
        ),
      ],
      'OR',
    )
  ) {
    return `/application/workspace/${item.id}/${item.type}/overview`
  } else if (
    hasPermission(
      [
        new ComplexPermission(
          [RoleConst.USER],
          [PermissionConst.APPLICATION.getApplicationWorkspaceResourcePermission(item.id)],
          [],
          'AND',
        ),
        RoleConst.WORKSPACE_MANAGE.getWorkspaceRole,
        PermissionConst.APPLICATION_EDIT.getWorkspacePermissionWorkspaceManageRole,
        PermissionConst.APPLICATION_EDIT.getApplicationWorkspaceResourcePermission(item.id),
      ],
      'OR',
    )
  ) {
    if (item.type == 'WORK_FLOW') {
      return `/application/workspace/${item.id}/workflow`
    } else {
      return `/application/workspace/${item.id}/${item.type}/setting`
    }
  } else if (
    hasPermission(
      [
        new ComplexPermission(
          [RoleConst.USER],
          [PermissionConst.APPLICATION.getApplicationWorkspaceResourcePermission(item.id)],
          [EditionConst.IS_EE, EditionConst.IS_PE],
          'AND',
        ),
        new ComplexPermission(
          [RoleConst.WORKSPACE_MANAGE.getWorkspaceRole],
          [PermissionConst.APPLICATION_ACCESS_READ.getWorkspacePermissionWorkspaceManageRole],
          [EditionConst.IS_EE, EditionConst.IS_PE],
          'OR',
        ),
        new ComplexPermission(
          [],
          [
            PermissionConst.APPLICATION_ACCESS_READ.getApplicationWorkspaceResourcePermission(
              item.id,
            ),
          ],
          [EditionConst.IS_EE, EditionConst.IS_PE],
          'OR',
        ),
      ],
      'OR',
    )
  ) {
    return `/application/workspace/${item.id}/${item.type}/access`
  } else if (
    hasPermission(
      [
        new ComplexPermission(
          [RoleConst.USER],
          [PermissionConst.APPLICATION.getApplicationWorkspaceResourcePermission(item.id)],
          [EditionConst.IS_EE, EditionConst.IS_PE],
          'AND',
        ),
        new ComplexPermission(
          [RoleConst.WORKSPACE_MANAGE.getWorkspaceRole],
          [PermissionConst.APPLICATION_CHAT_USER_READ.getWorkspacePermissionWorkspaceManageRole],
          [EditionConst.IS_EE, EditionConst.IS_PE],
          'OR',
        ),
        new ComplexPermission(
          [],
          [
            PermissionConst.APPLICATION_CHAT_USER_READ.getApplicationWorkspaceResourcePermission(
              item.id,
            ),
          ],
          [EditionConst.IS_EE, EditionConst.IS_PE],
          'OR',
        ),
      ],
      'OR',
    )
  ) {
    return `/application/workspace/${item.id}/${item.type}/chat-user`
  } else if (
    hasPermission(
      [
        new ComplexPermission(
          [RoleConst.USER],
          [PermissionConst.APPLICATION.getApplicationWorkspaceResourcePermission(item.id)],
          [],
          'AND',
        ),
        PermissionConst.APPLICATION_CHAT_LOG_READ.getWorkspacePermissionWorkspaceManageRole,
        PermissionConst.APPLICATION_CHAT_LOG_READ.getApplicationWorkspaceResourcePermission(
          item.id,
        ),
      ],
      'OR',
    )
  ) {
    return `/application/workspace/${item.id}/${item.type}/chat-log`
  } else return `/application/`
}

const CreateApplicationDialogRef = ref()

function openCreateDialog(type?: string) {
  CreateApplicationDialogRef.value.open(folder.currentFolder?.id || 'default', type)
}

const search_type_change = () => {
  search_form.value = { name: '', create_user: '' }
}

const apiInputParams = ref([])

function toChat(row: any) {
  row?.work_flow?.nodes
    ?.filter((v: any) => v.id === 'base-node')
    .map((v: any) => {
      apiInputParams.value = v.properties.api_input_field_list
        ? v.properties.api_input_field_list.map((v: any) => {
            return {
              name: v.variable,
              value: v.default_value,
            }
          })
        : v.properties.input_field_list
          ? v.properties.input_field_list
              .filter((v: any) => v.assignment_method === 'api_input')
              .map((v: any) => {
                return {
                  name: v.variable,
                  value: v.default_value,
                }
              })
          : []
    })
  const apiParams = mapToUrlParams(apiInputParams.value)
    ? '?' + mapToUrlParams(apiInputParams.value)
    : ''
  ApplicationApi.getAccessToken(row.id, loading).then((res: any) => {
    window.open(application.location + res?.data?.access_token + apiParams)
  })
}

function mapToUrlParams(map: any[]) {
  const params = new URLSearchParams()

  map.forEach((item: any) => {
    params.append(encodeURIComponent(item.name), encodeURIComponent(item.value))
  })

  return params.toString() // 返回 URL 查询字符串
}

function copyApplication(row: any) {
  ApplicationApi.getApplicationDetail(row.id, loading).then((res: any) => {
    if (res?.data) {
      CopyApplicationDialogRef.value.open(
        { ...res.data, model_id: res.data.model },
        folder.currentFolder?.id || 'default',
      )
    }
  })
}

function settingApplication(row: any) {
  if (isWorkFlow(row.type)) {
    router.push({ path: `/application/workspace/${row.id}/workflow` })
  } else {
    router.push({ path: `/application/workspace/${row.id}/${row.type}/setting` })
  }
}

function deleteApplication(row: any) {
  MsgConfirm(
    `${t('views.application.delete.confirmTitle')}${row.name} ?`,
    t('views.application.delete.confirmMessage'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      confirmButtonClass: 'danger',
    },
  )
    .then(() => {
      ApplicationApi.delApplication(row.id, loading).then(() => {
        const index = applicationList.value.findIndex((v) => v.id === row.id)
        applicationList.value.splice(index, 1)
        MsgSuccess(t('common.deleteSuccess'))
      })
    })
    .catch(() => {})
}

const exportApplication = (application: any) => {
  ApplicationApi.exportApplication(application.id, application.name, loading).catch((e) => {
    if (e.response.status !== 403) {
      e.response.data.text().then((res: string) => {
        MsgError(`${t('views.application.tip.ExportError')}:${JSON.parse(res).message}`)
      })
    }
  })
}

const elUploadRef = ref()
const importApplication = (file: any) => {
  const formData = new FormData()
  formData.append('file', file.raw, file.name)
  elUploadRef.value.clearFiles()
  ApplicationApi.importApplication(folder.currentFolder.id, formData, loading)
    .then(async (res: any) => {
      if (res?.data) {
        applicationList.value = []
        user.profile()
      }
    })
    .then(() => {
      getList()
    })
    .catch((e) => {
      if (e.code === 400) {
        MsgConfirm(t('common.tip'), t('views.application.tip.professionalMessage'), {
          cancelButtonText: t('common.confirm'),
          confirmButtonText: t('common.professional'),
        }).then(() => {
          window.open('https://maxkb.cn/pricing.html', '_blank')
        })
      }
    })
}

// 文件夹相关
const CreateFolderDialogRef = ref()

function openCreateFolder() {
  CreateFolderDialogRef.value.open(SourceTypeEnum.APPLICATION, folder.currentFolder.id)
}

function getFolder(bool?: boolean) {
  const params = {}
  folder.asyncGetFolder(SourceTypeEnum.APPLICATION, params, loading).then((res: any) => {
    // 确保根文件夹名称显示为'应用'
    if (res.data && res.data.length > 0 && res.data[0].id === 'default') {
      res.data[0].name = '应用'
    }
    folderList.value = res.data
    if (bool) {
      // 初始化刷新
      const currentFolder = res.data?.[0] || {}
      // 确保当前文件夹名称也显示为'应用'
      if (currentFolder.id === 'default') {
        currentFolder.name = '应用'
      }
      folder.setCurrentFolder(currentFolder)
    }
    getList()
  })
}

function clickFolder(item: any) {
  folder.setCurrentFolder(item)
  paginationConfig.current_page = 1
  applicationList.value = []
  getList()
}

function folderClickHandle(row: any) {
  if (row.id === folder.currentFolder?.id) {
    return
  }
  folder.setCurrentFolder(row)
  paginationConfig.current_page = 1
  applicationList.value = []
  getList()
}

function refreshFolder() {
  paginationConfig.current_page = 1
  applicationList.value = []
  getFolder()
}

function searchHandle() {
  paginationConfig.current_page = 1
  applicationList.value = []
  getList()
}

function getList() {
  const params: any = {
    folder_id: folder.currentFolder?.id || 'default',
  }
  if (search_form.value.name) {
    params.name = search_form.value.name
  }
  ApplicationApi.getApplication(paginationConfig, params, loading).then((res) => {
    paginationConfig.total = res.data.total
    applicationList.value = [...applicationList.value, ...res.data.records]
  })
}

onMounted(() => {
  getFolder(folder.currentFolder?.id ? false : true)
})
</script>

<style lang="scss" scoped>
// 完全隐藏LayoutContainer的左侧区域
:deep(.layout-container__left) {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
  overflow: hidden !important;
  visibility: hidden !important;
  position: absolute !important;
  z-index: -1 !important;
}

// 确保LayoutContainer完全占满宽度
.application-manage {
  width: 100% !important;
  max-width: none !important;
}

// 确保主内容区域完全占满整个宽度
:deep(.layout-container__right) {
  width: 100% !important;
  flex: none !important;
  margin: 0 !important;
  padding: 0 !important;
}

// 确保ContentContainer也占满宽度
:deep(.content-container) {
  width: 100% !important;
  max-width: none !important;
  padding: 0 !important;
}

// 隐藏所有相关的控制元素
:deep(.collapse-btn),
:deep(.toggle-sidebar),
:deep(.menu-toggle),
:deep(.collapse-trigger),
:deep(.sidebar-toggle),
:deep(.layout-sider-trigger) {
  display: none !important;
}

// 设置卡片网格的边距
:deep(.el-row) {
  margin: 0 !important;
}

:deep(.el-col) {
  padding: 0 16px 16px 0 !important;
}

// 确保滚动区域也占满宽度
:deep(.infinite-scroll-wrapper) {
  width: 100% !important;
  max-width: none !important;
}

/* 创建按钮样式 */
.create-button-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #dcdfe6;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.create-button-card:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.create-icon {
  margin-bottom: 8px;
}

.create-button-inner {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
</style>
